const http = require("http");
const path = require("path");
const fs = require("fs");
const mime = require("mime");
const url = require("url");
const server = http.createServer(function (req, res) {
  const urlObj = url.parse(req.url, true);
  const urlPathname = urlObj.pathname;

  const fileName = path.resolve(__dirname, "./3.render" + urlPathname);
  
  // const extName = path.extname(fileName).substr(1);

  // 解析后对象的 ext 属性中保存着目标文件的后缀名
  const ext = path.parse(urlPathname).ext;
  // 获取后缀对应的 MIME 类型
  const mimeType = mime.getType(ext);
  // console.log("filename", fileName, urlPathname, ext);
  if (fs.existsSync(fileName) && ext && mimeType) {
    //判断本地文件是否存在
    mimeType && res.setHeader("Content-Type", mimeType);
    let { delay } = urlObj.query;
    if ((ext == ".css" || ext == ".js" || '.jpg' || '.png') && delay) {
      setTimeout(() => {
        const stream = fs.createReadStream(fileName);
        stream.pipe(res);
      }, delay - 0);
    } else {
      const stream = fs.createReadStream(fileName);
      stream.pipe(res);
    }
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.write("404 - File is not found!");
    res.end();
  }
});
server.listen(10000, function () {
  console.log(`app listening at http://localhost:${10000}`);
});
